let mysql = require('mysql')
const debug = require('debug')('vue-common-demo-backend:Mysql')

let pool = mysql.createPool({
  host: '10.211.55.5',
  user: 'root',
  password: 'root',
  port: '3306',
  database: 'vue_common_demo',
  multipleStatements: true
})

pool.on('enqueue', function () {
  // debug('Waiting for available connection slot')
  debug('Waiting for available connection slot')

})

pool.on('release', function (connection) {
  // debug('Connection %d released', connection.threadId)
  debug('Connection %d released', connection.threadId)
})

module.exports = {
  pool: pool,
  query (sql, options) {
    return new Promise((resolve, reject) => {
      pool.getConnection((err, conn) => {
        if (err) {
          // 回调
          debug(err)
          reject(err)
        } else {
          conn.query(sql, options, (err, results, fields) => {
            // 释放链接
            conn.release()
            // 回调
            if (err) {
              // 异常
              debug('数据操作异常')
              reject(err)
            } else {
              // 正常
              resolve({results, fields})
            }
          })
        }
      })
    })
  },
  transaction (sql, options) {
    return new Promise((resolve, reject) => {
      pool.getConnection((err, conn) => {
        if (err) {
          // 回调
          debug(err)
          reject(err)
        } else {
          conn.beginTransaction(() => {
            if (err) {
              reject(err)
            }
            conn.query(sql, options, (err, results, fields) => {
              // 释放链接
              conn.release()
              // 回调
              if (err) {
                return conn.rollback(() => {
                  // 异常
                  debug('事务操作异常，回滚')
                  reject(err)
                })
              } else {
                conn.commit((err) => {
                  if (err) {
                    return conn.rollback(() => {
                      // 异常
                      debug('事务操作异常，回滚')
                      reject(err)
                    })
                  } else {
                    // 正常
                    resolve({results, fields})
                  }
                })
              }
            })
          })
        }
      })
    })
  }
}